<template>
  <div class="createEdit-container">
    <div class="app-title-container title-position">
      <modules-title :title-name="projectId?'编辑自研立项':'创建自研立项'" style="margin-bottom: 20px;">
        <template slot="btn">
          <el-button plain @click="goBack">返回</el-button>
          <!-- <el-button v-if="!projectId" plain @click="resetForm">重置</el-button> -->
          <el-button type="primary" @click="saveForm">保存草稿</el-button>
          <el-button type="primary" @click="submitForm">启动调研</el-button>
        </template>
      </modules-title>
    </div>
    <div class="main-content-container">

      <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="120px">

        <el-row
          :gutter="15"
          class="form-row01"
          style="margin-left:0px;margin-right:0px;display:flex;justify-content:space-between;flex-wrap:wrap;"
        >
          <el-form-item label="关联项目课题" prop="demand_idea_name" style="width:50%">
            <el-autocomplete
              v-model="formData.demand_idea_name"
              :disabled="projectId!==''"
              :fetch-suggestions="requireQuerySearchAsync"
              placeholder="可模糊搜索同意采纳未提交立项的课题"
              style="width:100%;"
              @select="handleSelect"
              @change="requireChange"
            >
              <template slot="suffix">
                <el-tooltip content="可模糊搜索同意采纳未提交立项的课题快速创建立项项目" placement="bottom" effect="light">
                  <i class="el-icon-warning" />
                </el-tooltip>
              </template>
              <template slot-scope="{item}">
                <div class="name">{{ item.project_name }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="项目来源" prop="project_source_id" style="width:50%">
            <el-select
              v-model="formData.project_source_id"
              disabled
              placeholder="请选择项目来源"
              filterable
              clearable
              :style="{width: '100%'}"
              @change="projectSourceChange"
            >
              <el-option
                v-for="(item, index) in projectSourceOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="申请项目名称" prop="project_name" style="width:50%;">
            <el-input
              v-model="formData.project_name"
              placeholder="请输入申请项目名称"
              clearable
              :style="{width: '100%'}"
            />
          </el-form-item>
          <el-form-item label="项目类型" prop="project_type_id" style="width:50%">
            <el-select
              v-model="formData.project_type_id"
              placeholder="请选择项目类型"
              clearable
              :style="{width: '100%'}"
              @change="projectTypeChange"
            >
              <el-option
                v-for="(item, index) in projectTypeOptions"
                :key="index"
                :label="item.dict_val"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="申报类别" prop="apply_type_id" style="width:50%">
            <el-select
              v-model="formData.apply_type_id"
              placeholder="请选择申报类别"
              clearable
              :style="{width: '100%'}"
              @change="applyTypeChange"
            >
              <el-option
                v-for="(item, index) in applyTypeOptions"
                :key="index"
                :label="item.dict_val"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药物类别" prop="medical_type" style="width:50%">
            <el-input
              v-model="formData.medical_type"
              placeholder="请输入药物类别"
              clearable
              :style="{width: '100%'}"
            />
          </el-form-item>
          <el-form-item label="剂型与规格" prop="dosage_norms" style="width:50%">
            <el-input
              v-model="formData.dosage_norms"
              placeholder="请输入剂型与规格"
              clearable
              :style="{width: '100%'}"
            />
          </el-form-item>
          <el-form-item label="药物成分" prop="medical_ingredient" style="width:50%">
            <el-input
              v-model="formData.medical_ingredient"
              placeholder="请输入药物成分"
              clearable
              :style="{width: '100%'}"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="15" style="margin-left:0px;margin-right:0px;">
          <el-form-item label="功能主治" prop="function_attending" style="width:100%">
            <el-input
              v-model="formData.function_attending"
              placeholder="请输入功能主治"
              clearable
              :style="{width: '100%'}"
            />
          </el-form-item>
          <el-form-item label="质量标准来源" prop="quality_source">
            <el-input
              v-model="formData.quality_source"
              type="textarea"
              placeholder="请输入质量标准来源"
              :autosize="{minRows: 3, maxRows: 6}"
              :style="{width: '100%'}"
            />
          </el-form-item>
          <el-form-item label="附件">
            <!-- <upload ref="upload" :edit-list="formData.enclosure" :project-data="{project_id: 'projectInfo',validation: 1}" @uploadSuccess="uploadSuccess" @deleteSuccess="deleteSuccess" /> -->
            <upload-select ref="upload" :edit-list="formData.enclosure" :project-data="{project_id: 'demand_info',validation: 1}" @uploadSuccess="uploadSuccess" @deleteSuccess="deleteSuccess" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>

</template>
<script>
import {
  creatProjectInfo,
  projectInfoDetail,
  editProjectInfo,
  submitResearch
} from '@/api/projectInformation'
import { searchPassRequire, requirementDetail } from '@/api/requirement'

export default {
  components: {},
  data() {
    return {
      formData: {
        demand_idea_id: '',
        demand_idea_name: '',
        project_name: '',
        project_source: '自研',
        project_source_id: '1',
        project_type: '',
        project_type_id: '',
        medical_type: '',
        apply_type: '',
        apply_type_id: '',
        function_attending: '',
        dosage_norms: '',
        medical_ingredient: '',
        quality_source: '',
        enclosure: []
      },
      requireId: '', // 有值说明是通过需求快速创建
      // 编辑
      projectId: '',
      detailData: null,
      rules: {
        project_name: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        project_source_id: [
          {
            required: true,
            message: '请选择项目来源',
            trigger: 'change'
          }
        ],
        project_type_id: [
          {
            required: true,
            message: '请选择项目类型',
            trigger: 'change'
          }
        ],
        medical_type: [
          {
            required: true,
            message: '请输入药物类别',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        apply_type_id: [
          {
            required: true,
            message: '请选择申报类别',
            trigger: 'change'
          }
        ],
        function_attending: [
          {
            required: true,
            message: '请输入适应症',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        dosage_norms: [
          {
            required: true,
            message: '请输入剂型与规格',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        medical_ingredient: [
          {
            required: true,
            message: '请输入药物成分',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        quality_source: []
      },
      projectSourceOptions: [
        {
          label: '自研',
          value: '1'
        },
        {
          label: '委托',
          value: '2'
        }
      ],
      projectTypeOptions: [],
      applyTypeOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getSysAllDic()
    // 获取需求id
    this.requireId = this.$route.query.requireId || ''
    // 通过projectId判断创建与编辑
    this.projectId = this.$route.query.projectId || ''
    if (this.projectId) {
      this.getprojectInfoDetail(this.projectId)
    } else {
      if (this.requireId) {
        // 获取需求详情
        this.getRequirementDetail(this.requireId)
      }
    }
  },
  mounted() {},
  methods: {
    // 返回之后刷新列表
    refreshBack() {
      this.$route.params.refresh = true
      this.$router.back()
    },
    goBack() {
      this.$router.back()
    },
    // 项目来源选择改变
    projectSourceChange(val) {
      const obj = this.projectSourceOptions.find((itm) => {
        return itm.value === val
      })
      this.formData.project_source = obj.label
      console.log(val, this.formData)
    },
    // 项目类型改变
    projectTypeChange(val) {
      const obj = this.projectTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.project_type = obj.dict_val
      console.log(val, this.formData)
    },
    // 申报类别改变
    applyTypeChange(val) {
      const obj = this.applyTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.apply_type = obj.dict_val
      console.log(val, this.formData)
    },
    getSysAllDic() {
      let allDic = this.$store.getters.sysDic()
      if (!allDic) {
        this.$store.dispatch('sys/getSysAllDic').then(data => {
          allDic = data
        })
      }
      console.log(allDic)
      this.projectTypeOptions = allDic['project_type']
      this.applyTypeOptions = allDic['apply_type']
    },
    // 立项创建
    saveCreatProjectInfo(isBack = true) {
      const datas = {
        demand_idea_id: this.formData.demand_idea_id,
        demand_idea_name: this.formData.demand_idea_name,
        demand_info: {
          project_name: this.formData.project_name,
          project_source: this.formData.project_source,
          project_source_id: this.formData.project_source_id,
          project_type: this.formData.project_type,
          project_type_id: this.formData.project_type_id,
          medical_type: this.formData.medical_type,
          apply_type: this.formData.apply_type,
          apply_type_id: this.formData.apply_type_id,
          function_attending: this.formData.function_attending,
          dosage_norms: this.formData.dosage_norms,
          medical_ingredient: this.formData.medical_ingredient,
          quality_source: this.formData.quality_source,
          enclosure: this.formData.enclosure
        }
      }
      creatProjectInfo(datas).then((res) => {
        if (res.code === 200) {
          if (isBack) {
            this.refreshBack()
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
            duration: 1500
          })
        }
      })
    },
    getRequirementDetail(id) {
      requirementDetail(id).then((res) => {
        if (res.code === 200) {
          this.detailData = res.data
          // this.formData = this.detailData;
          this.formData.demand_idea_id = this.detailData.id
          this.formData.demand_idea_name = this.detailData.project_name
          this.formData.project_name = this.detailData.project_name
          this.formData.project_type = this.detailData.project_type
          this.formData.project_type_id = this.detailData.project_type_id
          this.formData.medical_type = this.detailData.medical_type
          this.formData.apply_type = this.detailData.apply_type
          this.formData.apply_type_id = this.detailData.apply_type_id
          this.formData.function_attending = this.detailData.function_attending
          this.formData.dosage_norms = this.detailData.dosage_norms
          this.formData.medical_ingredient = this.detailData.medical_ingredient
          this.formData.quality_source = this.detailData.quality_source
          // this.formData.enclosure = this.detailData.enclosure
        }
      })
    },
    deleteSuccess() {
      // this.formData.enclosure = this.$refs.upload.emitFileList()
    },
    uploadSuccess() {
      // this.formData.enclosure = this.$refs.upload.emitFileList()
    },
    // 编辑立项信息
    updateProjectInfo(isBack = true) {
      editProjectInfo(this.formData).then((res) => {
        if (res.code === 200) {
          if (isBack) {
            this.refreshBack()
          }
        }
      })
    },
    // 获取立项详情
    getprojectInfoDetail(id) {
      const datas = { id: id }
      projectInfoDetail(datas).then((res) => {
        if (res.code === 200) {
          this.detailData = res.data
          this.formData = this.detailData
        }
      })
    },
    submitForm() {
      const that = this
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        // ToDo 提交表单
        that.$refs.upload.saveFile().then((dataList) => {
          that.formData.enclosure = dataList[0]
          that.submitCheck()
        }).catch(err => {
          console.log(err)
        })
      })
    },
    submitResearchOperation() {
      const datas = {
        id: this.projectId
      }
      submitResearch(datas).then((res) => {
        if (res.code === 200) {
          this.refreshBack()
        }
      })
    },
    async submitCheck() {
      const that = this
      let saveRes = null
      if (that.projectId) {
        saveRes = await editProjectInfo(this.formData)
      } else {
        const datas = {
          demand_idea_id: this.formData.demand_idea_id,
          demand_idea_name: this.formData.demand_idea_name,
          demand_info: {
            project_name: this.formData.project_name,
            project_source: this.formData.project_source,
            project_source_id: this.formData.project_source_id,
            project_type: this.formData.project_type,
            project_type_id: this.formData.project_type_id,
            medical_type: this.formData.medical_type,
            apply_type: this.formData.apply_type,
            apply_type_id: this.formData.apply_type_id,
            function_attending: this.formData.function_attending,
            dosage_norms: this.formData.dosage_norms,
            medical_ingredient: this.formData.medical_ingredient,
            quality_source: this.formData.quality_source,
            enclosure: this.formData.enclosure
          }
        }
        saveRes = await creatProjectInfo(datas)
      }
      if (saveRes.code === 200) {
        const subRes = await submitResearch({ id: saveRes.data.id })
        if (subRes && subRes.code === 200) {
          this.refreshBack()
        } else {
          this.$message({
            type: 'error',
            message: subRes.msg,
            onClose: () => {
              this.refreshBack()
            }
          })
        }
      } else {
        this.$message({
          type: 'error',
          message: saveRes.msg
        })
      }
    },
    saveForm() {
      const that = this

      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        // ToDo 提交表单
        this.$refs.upload.saveFile().then((dataList) => {
          this.formData.enclosure = dataList[0]
          // 判断是编辑还是初次创建
          if (that.projectId) {
            that.updateProjectInfo()
          } else {
            that.saveCreatProjectInfo()
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },
    resetForm() {
      this.formData = {
        demand_idea_id: '',
        demand_idea_name: '',
        project_name: '',
        project_source: '自研',
        project_source_id: '1',
        project_type: '',
        project_type_id: '',
        medical_type: '',
        apply_type: '',
        apply_type_id: '',
        function_attending: '',
        dosage_norms: '',
        medical_ingredient: '',
        quality_source: '',
        enclosure: []
      }
      this.$refs['upload'].resetFileList()
      this.$refs['elForm'].resetFields() // 重置表单，clear不起作用
      console.log(this.formData)
    },
    // 课题输入联想
    async requireQuerySearchAsync(queryString, cb) {
      const res = await searchPassRequire({ select_str: queryString })
      var restaurants = res.data.data || []
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants

      cb(results)
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.project_name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    handleSelect(item) {
      console.log(item)
      this.formData.demand_idea_id = item.id
      this.formData.demand_idea_name = item.project_name
      this.formData.project_name = item.project_name
      this.formData.project_type = item.project_type
      this.formData.project_type_id = item.project_type_id
      this.formData.medical_type = item.medical_type
      this.formData.apply_type = item.apply_type
      this.formData.apply_type_id = item.apply_type_id
      this.formData.function_attending = item.function_attending
      this.formData.dosage_norms = item.dosage_norms
      this.formData.medical_ingredient = item.medical_ingredient
      this.formData.quality_source = item.quality_source
      // this.formData.enclosure = item.enclosure // 需求附件不需要带
    },
    requireChange() {
      this.resetForm()
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/scss/views/projectInfomation/createEdit/createEdit.scss";
</style>
